package com.zhiyizhen.handheld.component.execute;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zhiyizhen.handheld.R;
import com.zhiyizhen.handheld.common.AppUtil;
import com.zhiyizhen.handheld.common.DataCache;
import com.zhiyizhen.handheld.common.DateUtil;
import com.zhiyizhen.handheld.common.ImageLoader;
import com.zhiyizhen.handheld.common.LogUtil;
import com.zhiyizhen.handheld.common.RxJavaUtil;
import com.zhiyizhen.handheld.common.StringUtil;
import com.zhiyizhen.handheld.common.ToastUtil;
import com.zhiyizhen.handheld.common.event.AddNewRecordEvent;
import com.zhiyizhen.handheld.common.event.ChangeExecuteStatusEvent;
import com.zhiyizhen.handheld.common.view.BaseFragment;
import com.zhiyizhen.handheld.common.view.CommonDialog;
import com.zhiyizhen.handheld.component.execute.adapter.ExecuteDetailShuyeAdapter;
import com.zhiyizhen.handheld.component.execute.adapter.ExecuteDetailWaizhiAdapter;
import com.zhiyizhen.handheld.component.execute.api.IExecuteService;
import com.zhiyizhen.handheld.component.execute.bean.executedetail.ExecuteDetailBean;
import com.zhiyizhen.handheld.component.execute.bean.executedetail.GroupListItem;
import com.zhiyizhen.handheld.component.execute.bean.req.AddExecRecordReq;
import com.zhiyizhen.handheld.component.execute.bean.req.AddInfusionFeeReq;
import com.zhiyizhen.handheld.component.login.bean.LoginBean;
import com.zhiyizhen.handheld.component.main.bean.EnumsBean;
import com.zhiyizhen.handheld.databinding.FragmentShuyeDetailBinding;
import com.zhiyizhen.handheld.net.ServiceFactory;
import com.zhiyizhen.handheld.net.response.ResponseData;
import com.zhiyizhen.handheld.net.response.ResponseObserver;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

public class ShuyeDetailFragment extends BaseFragment {
    private FragmentShuyeDetailBinding binding;
    private LoginBean loginBean;

    private String orderId;
    private EnumsBean enumsBean;
    private RecyclerView mRecyclerView;
    private ExecuteDetailShuyeAdapter shuyeAdapter;
    private ExecuteDetailWaizhiAdapter waizhiAdapter;
    private ExecuteDetailBean data;

    public void setExtraData(EnumsBean enumsBean, String orderId) {
        this.orderId = orderId;
        this.enumsBean = enumsBean;
        getDetail(orderId);
        binding.executeLayout.setVisibility(View.VISIBLE);
        binding.emptyView.setVisibility(View.GONE);
    }

    public void setEmptyData() {
        binding.executeLayout.setVisibility(View.GONE);
        binding.emptyView.setVisibility(View.VISIBLE);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentShuyeDetailBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        loginBean = DataCache.getLoginBean();
        initView();
    }

    private void initView() {
        mRecyclerView = binding.recyclerView;
        shuyeAdapter = new ExecuteDetailShuyeAdapter(getContext());
        waizhiAdapter = new ExecuteDetailWaizhiAdapter(getContext());

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        shuyeAdapter.setOnActionClickListener(new ExecuteDetailShuyeAdapter.OnActionClickListener() {
            @Override
            public void onAddCharge(ExecuteDetailBean.RxInfoBean data) {
                showAddChargeDialog();
            }

            @Override
            public void onAddExecuteRecord(GroupListItem data) {
                showAddExecuteDialog(data);
            }
        });

        waizhiAdapter.setOnActionClickListener(this::showAddWaizhiExecuteDialog);
    }

    private CommonDialog dialog;

    public void showAddExecuteDialog(GroupListItem data) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_execute, (ViewGroup) getActivity().getWindow().getDecorView(), false);
        final TextView executeTimesTv = view.findViewById(R.id.executeTimesTv);
        final TextView executeNameTv = view.findViewById(R.id.executeNameTv);
        final EditText executeResultEdit = view.findViewById(R.id.executeResultEdit);
        final TextView executeTimeTv = view.findViewById(R.id.executeTimeTv);

        executeTimesTv.setText(String.format(Locale.getDefault(), "本次为第 %1$d 次执行，剩余 %2$d 次。", data.getNextTimes(), data.getTotalTimes() - data.getNextTimes()));
        executeNameTv.setText(String.format("执行人：%1$s", loginBean.getEmpName()));
        executeTimeTv.setText(String.format("执行时间：%1$s", DateUtil.getCurrentTime()));
        CommonDialog.Builder builder = new CommonDialog.Builder(getActivity());
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_button).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.okBtn).setOnClickListener(v -> {
            String executeResult = executeResultEdit.getText().toString().trim();
            if (TextUtils.isEmpty(executeResult)) {
                ToastUtil.showShort("请输入执行效果");
                return;
            }
            addExecRecord(data.getGroupName(), executeResultEdit.getText().toString().trim());
        });
    }

    public void showAddWaizhiExecuteDialog(ExecuteDetailBean.RxInfoBean data) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_execute, (ViewGroup) getActivity().getWindow().getDecorView(), false);
        final TextView executeTimesTv = view.findViewById(R.id.executeTimesTv);
        final TextView executeNameTv = view.findViewById(R.id.executeNameTv);
        final EditText executeResultEdit = view.findViewById(R.id.executeResultEdit);
        final TextView executeTimeTv = view.findViewById(R.id.executeTimeTv);

        executeTimesTv.setText(String.format(Locale.getDefault(), "本次为第 %1$d 次执行，剩余 %2$d 次。", data.getExtInfo().getNextTimes(), data.getExtInfo().getTotalTimes() - data.getExtInfo().getNextTimes()));
        executeNameTv.setText(String.format("执行人：%1$s", loginBean.getEmpName()));
        executeTimeTv.setText(String.format("执行时间：%1$s", DateUtil.getCurrentTime()));
        CommonDialog.Builder builder = new CommonDialog.Builder(getActivity());
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_button).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.okBtn).setOnClickListener(v -> {
            String executeResult = executeResultEdit.getText().toString().trim();
            if (TextUtils.isEmpty(executeResult)) {
                ToastUtil.showShort("请输入执行效果");
                return;
            }
            addExecRecord(data.getRxName(), executeResultEdit.getText().toString().trim());
        });
    }

    public void showAddChargeDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_injection, (ViewGroup) getActivity().getWindow().getDecorView(), false);
        final EditText executeTimesTv = view.findViewById(R.id.chargeEdit);

        CommonDialog.Builder builder = new CommonDialog.Builder(getActivity());
        builder.setView(view);

        builder.setCancelable(false);
        dialog = builder.show();

        view.findViewById(R.id.cancel_button).setOnClickListener(v -> dialog.dismiss());
        view.findViewById(R.id.okBtn).setOnClickListener(v -> {
            String amountString = executeTimesTv.getText().toString().trim();
            if (!AppUtil.isPureDigital(amountString)) {
                ToastUtil.showShort("请输入正整数");
                return;
            }
            try {
                int amount = Integer.parseInt(amountString);
                addInfusionFee(amount * 100);
            } catch (NumberFormatException e) {
                LogUtil.e(e);
            }
        });
    }

    private void setData(ExecuteDetailBean data) {
        this.data = data;
        if ("1".equals(data.getPatientGender())) {
            ImageLoader.load(getContext(), R.drawable.icon_man, binding.genderImg);
        } else if ("2".equals(data.getPatientGender())) {
            ImageLoader.load(getContext(), R.drawable.icon_woman, binding.genderImg);
        } else {
            ImageLoader.load(getContext(), R.drawable.icon_unknow, binding.genderImg);
        }
        binding.genderTv.setText(StringUtil.getGender(data.getPatientGender(), enumsBean));

        binding.userNameTv.setText(data.getPatientName());
        binding.doctorNameTv.setText(data.getDoctorName());
        binding.ageTv.setText(StringUtil.getAge(data.getAgeYear(), data.getAgeMonth()));
        if (!TextUtils.isEmpty(data.getWeight())) {
            binding.weightTv.setText(data.getWeight() + "kg");
            binding.divideLeftOfWeight.setVisibility(View.VISIBLE);
        } else {
            binding.weightTv.setText(null);
            binding.divideLeftOfWeight.setVisibility(View.GONE);
        }
        if (data.getSystolicBp() != null && data.getDiastolicBp() != null) {
            binding.bloodPressureTv.setText(data.getSystolicBp() + "/" + data.getDiastolicBp() + " mmHg");
            binding.divideLeftOfBlood.setVisibility(View.VISIBLE);
        } else {
            binding.bloodPressureTv.setText(null);
            binding.divideLeftOfBlood.setVisibility(View.GONE);
        }

        binding.executeTypeTv.setText(StringUtil.getExecuteType(enumsBean.getDicts().getExecTypeBeanList(), data.getExecType()));
        binding.deptNameTv.setText(data.getDeptName());
        binding.visitDateTv.setText(data.getDiagnosisTime());

        if (TextUtils.equals(data.getExecType(), "SY")) {
            mRecyclerView.setAdapter(shuyeAdapter);
            List<ExecuteDetailBean.RxInfoBean> list = new ArrayList<>();
            list.add(data.getRxInfo());
            shuyeAdapter.setData(list);
        } else {
            mRecyclerView.setAdapter(waizhiAdapter);
            List<ExecuteDetailBean.RxInfoBean> list = new ArrayList<>();
            list.add(data.getRxInfo());
            waizhiAdapter.setData(list);
        }
    }

    private void getDetail(String orderId) {
        ServiceFactory.getService(IExecuteService.class)
                .getExecDetail(loginBean.getToken(), loginBean.getClinicId(), orderId)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<ExecuteDetailBean> responseData) {
                        if (responseData != null && responseData.getData() != null) {
                            setData(responseData.getData());
                        }
                    }
                });
    }

    private void addInfusionFee(int amount) {
        AddInfusionFeeReq addInfusionFeeReq = new AddInfusionFeeReq();
        addInfusionFeeReq.setOrderId(orderId);
        addInfusionFeeReq.setAmount(amount);
        ServiceFactory.getService(IExecuteService.class)
                .addInfusionFee(loginBean.getToken(), loginBean.getClinicId(), addInfusionFeeReq)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        ToastUtil.showShort("操作成功");
                        dialog.dismiss();
                        EventBus.getDefault().post(new AddNewRecordEvent(AddNewRecordEvent.CHARGE_RECORD_SHUYE));
                    }
                });
    }

    private void addExecRecord(String groupName, String execResult) {
        AddExecRecordReq addExecRecordReq = new AddExecRecordReq();
        addExecRecordReq.setOrderId(orderId);
        addExecRecordReq.setExecResult(execResult);
        if (!TextUtils.isEmpty(groupName)) {
            addExecRecordReq.setGroupName(groupName);
        }
        ServiceFactory.getService(IExecuteService.class)
                .addExecRecord(loginBean.getToken(), loginBean.getClinicId(), addExecRecordReq)
                .compose(RxJavaUtil.mainSchedulers())
                .as(this.bindLifecycle())
                .subscribe(new ResponseObserver<>() {
                    @Override
                    protected void onSuccess(ResponseData<String> responseData) {
                        ToastUtil.showShort("操作成功");
                        dialog.dismiss();
                        EventBus.getDefault().post(new AddNewRecordEvent(AddNewRecordEvent.EXECUTE_RECORD_SHUYE));

                        updateStatus(groupName);
                    }
                });
    }

    private void updateStatus(String groupName) {
        getDetail(orderId);
        if (TextUtils.equals(data.getExecType(), "SY")) {
            for (GroupListItem groupListItem : data.getRxInfo().getGroupList()) {
                if (TextUtils.equals(groupListItem.getGroupName(), groupName)) {
                    groupListItem.setExecStatus("3");
                    shuyeAdapter.notifyDataSetChanged();
                    break;
                }
            }

            boolean isAllExecute = true;
            for (GroupListItem groupListItem : data.getRxInfo().getGroupList()) {
                if (TextUtils.equals(groupListItem.getExecStatus(), "1") || TextUtils.equals(groupListItem.getExecStatus(), "2")) {
                    isAllExecute = false;
                    break;
                }
                if (!Objects.equals(groupListItem.getNextTimes(), groupListItem.getTotalTimes())) {
                    isAllExecute = false;
                    break;
                }
            }
            if (isAllExecute) {
                EventBus.getDefault().post(new ChangeExecuteStatusEvent(orderId));
            }
        } else {
            data.getRxInfo().getExtInfo().setExecStatus("3");
            waizhiAdapter.notifyDataSetChanged();
            if (Objects.equals(data.getRxInfo().getExtInfo().getNextTimes(), data.getRxInfo().getExtInfo().getTotalTimes())) {
                EventBus.getDefault().post(new ChangeExecuteStatusEvent(orderId));
            }

        }
    }

}
